package cloud.seri.gateway.security.oauth2

import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor

import javax.servlet.http.HttpServletRequest

/**
 * Extracts the access token from a cookie.
 * Falls back to a [BearerTokenExtractor] extracting information from the Authorization header, if no
 * cookie was found.
 */
class CookieTokenExtractor : BearerTokenExtractor()
{
    /**
     * Extract the JWT access token from the request, if present.
     * If not, then it falls back to the [BearerTokenExtractor] behaviour.
     *
     * @param request the request containing the cookies.
     * @return the extracted JWT token; or `null`.
     */
    override fun extractToken(request: HttpServletRequest): String?
    {
        val accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(request)
        return if (accessTokenCookie != null)
        {
            accessTokenCookie.value
        }
        else
        {
            super.extractToken(request)
        }
    }

}
